package com.xbongbong.paas.service.impl;

import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.pojo.dto.CallBlockRuleDTO;
import com.xbongbong.paas.pojo.dto.CallSetEffectiveTimeDTO;
import com.xbongbong.paas.pojo.dto.CallSwitchAutoOpenDetailDTO;
import com.xbongbong.paas.pojo.dto.CallSwitchAutoOpenDisturbDTO;
import com.xbongbong.paas.pojo.dto.CallSwitchBatchCallDTO;
import com.xbongbong.paas.pojo.vo.CallBlockRuleVO;
import com.xbongbong.paas.pojo.vo.CallCenterConfigVO;
import com.xbongbong.paas.pojo.vo.CallSetEffectiveTimeVO;
import com.xbongbong.paas.pojo.vo.CallSwitchAutoOpenDetailVO;
import com.xbongbong.paas.pojo.vo.CallSwitchAutoOpenDisturbVO;
import com.xbongbong.paas.pojo.vo.CallSwitchBatchCallVO;
import com.xbongbong.paas.pojo.vo.DuYanOrganizationVO;
import com.xbongbong.paas.service.CallCenterConfigService;
import com.xbongbong.paas.service.CallCenterOrganizationService;
import com.xbongbong.paas.service.DuYanHttpService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.enums.CallCenterTypeEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.CallCenterErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.XbbCallTaskLogConstant;
import com.xbongbong.saas.domain.entity.CallCenterConfigEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.CallCenterConfigModel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author youli.chen
 * @version v1.0
 * @description: 呼叫中心配置业务实现类
 * @date 2019/2/13 14:03
 * @since v1.0
 */
@Service("callCenterConfigService")
public class CallCenterConfigServiceImpl implements CallCenterConfigService {

    private static final Logger LOG = LoggerFactory.getLogger(CallCenterConfigServiceImpl.class);

    @Resource
    private CallCenterConfigModel callCenterConfigModel;
    @Resource
    private DuYanHttpService duYanHttpService;
    @Resource
    private CallCenterOrganizationService callCenterOrganizationService;

    /**
     * 获取该公司的话务中心设置，如果没有则新建
     *
     * @param corpid 公司id
     * @return 设置的持久层对象
     * @author youli.chen
     * @version v1.0
     * @since v1.0
     */
    @Override
    public XbbResponse<CallCenterConfigVO> getByCorpId(String corpid, Integer moduleType) throws XbbException {
        CallCenterConfigVO callCenterConfigVO = new CallCenterConfigVO();
        Map<String, Object> params = new HashMap<>(4);
        params.put("corpid", corpid);
        params.put("del", DelEnum.NORMAL.getDel());
        params.put("start", 0);
        params.put("pageNum", 1);
        List<CallCenterConfigEntity> list = callCenterConfigModel.findEntitys(params);
        if (list.size() == 0) {
            // 不存在则新建
            CallCenterConfigEntity configEntity = new CallCenterConfigEntity(corpid);
            if (callCenterConfigModel.insert(configEntity) > 0) {
                // 插入成功
                BeanUtils.copyProperties(configEntity, callCenterConfigVO);
            } else {
                LOG.error("公司（%s）插入话务中心设置失败！", corpid);
                callCenterConfigVO = null;
            }
        } else if (list.size() == 1) {
            BeanUtils.copyProperties(list.get(0), callCenterConfigVO);
        } else {
            LOG.error("【脏数据】公司（%s）存在多条话务中心设置！", corpid);
            for (int i = 1; i < list.size(); i++) {
                // 清理脏数据
                callCenterConfigModel.deleteByKey(list.get(i).getId(), corpid);
            }
            BeanUtils.copyProperties(list.get(0), callCenterConfigVO);
        }

        // 换卡服务充值信息
        Integer callBlockServer = BasicConstant.ZERO;
        if(moduleType != null && Objects.equals(moduleType, XbbRefTypeEnum.CALL_CENTER_XBB.getCode())){
            callBlockServer = callCenterOrganizationService.callBlockServer(corpid, moduleType);
        }
        callCenterConfigVO.setCallBlockServer(callBlockServer);
        return new XbbResponse<>(callCenterConfigVO);
    }

    /**
     * 开关自动打开详情开关(来电是否自动弹出客户详情)
     *
     * @param callSwitchAutoOpenDetailDTO 开关自动打开详情开关(来电是否自动弹出客户详情)入参
     * @return CallSwitchAutoOpenDetailVO 开关自动打开详情开关(来电是否自动弹出客户详情)回参
     * @throws XbbException 销帮帮设定的异常
     * @author youli.chen
     * @version v1.0
     * @since v1.0
     */
    @Override
    public XbbResponse<CallSwitchAutoOpenDetailVO> switchAutoOpenDetail(CallSwitchAutoOpenDetailDTO callSwitchAutoOpenDetailDTO) throws XbbException {
        CallSwitchAutoOpenDetailVO openDetailVO = new CallSwitchAutoOpenDetailVO();
        String type = callSwitchAutoOpenDetailDTO.getType();
        Integer moduleType = callSwitchAutoOpenDetailDTO.getModuleType();
        XbbResponse<CallCenterConfigVO> configResponse = getByCorpId(callSwitchAutoOpenDetailDTO.getCorpid(), moduleType);
        CallCenterConfigVO callCenterConfigVO = configResponse.getResult();
        if (callCenterConfigVO == null) {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301051);
        }
        CallCenterConfigEntity configEntity = new CallCenterConfigEntity();
        BeanUtils.copyProperties(callCenterConfigVO, configEntity);
        // 来电弹屏
        if (Objects.equals(type, XbbCallTaskLogConstant.AUTO_OPEN_DATAIL)) {
            configEntity.setIsAutoOpenDetail(configEntity.getIsAutoOpenDetail() == 1 ? 0 : 1);
            // 隐藏号码段
        } else if (Objects.equals(type, XbbCallTaskLogConstant.SHOW_PHONE)) {
            configEntity.setIsShowPhone(configEntity.getIsShowPhone() == 1 ? 0 : 1);
            //以上为通话记录号码段处理,与以下度言号码段隐藏互不冲突
            if (moduleType == CallCenterTypeEnum.CALL_CENTER_DU_YAN.getCode()) {
                String apiKey = callCenterOrganizationService.getApiKey(callSwitchAutoOpenDetailDTO.getCorpid(), moduleType);
                if (StringUtils.isNotEmpty(apiKey)) {
                    String orgPhoneProtection = configEntity.getIsShowPhone() == 1 ? "PUBLIC" : "PRIVATE";
                    DuYanOrganizationVO duYanOrganizationVO = duYanHttpService.getCompanyMsg(apiKey);
                    String code = duYanHttpService.updateCompanyPhone(apiKey, duYanOrganizationVO.getOrgId(), orgPhoneProtection);
                    if (Objects.equals(code, 1)) {
                        LOG.info("企业所有团队客户号码状态设置成功！");
                    }
                }
            }
        }
        Integer switchAutoOpenDetail = callCenterConfigModel.update(configEntity);
        if (switchAutoOpenDetail > 0) {
            openDetailVO.setIsAutoOpenDetail(configEntity.getIsAutoOpenDetail());
            openDetailVO.setIsShowPhone(configEntity.getIsShowPhone());
        } else {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301073);
        }
        return new XbbResponse<>(openDetailVO);
    }

    /**
     * 开启批量外呼（主要是销帮帮呼叫中心）
     *
     * @param callSwitchBatchCallDTO 开启批量外呼（主要是销帮帮呼叫中心）入参
     * @return CallSwitchBatchCallVO 开启批量外呼（主要是销帮帮呼叫中心）回参
     * @throws XbbException 销帮帮设定的异常
     * @author youli.chen
     * @version v1.0
     * @since v1.0
     */
    @Override
    public XbbResponse<CallSwitchBatchCallVO> switchBatchCall(CallSwitchBatchCallDTO callSwitchBatchCallDTO) throws XbbException {
        CallSwitchBatchCallVO callSwitchBatchCallVO = new CallSwitchBatchCallVO();
        XbbResponse<CallCenterConfigVO> configResponse = getByCorpId(callSwitchBatchCallDTO.getCorpid(), null);
        CallCenterConfigVO callCenterConfigVO = configResponse.getResult();
        if (callCenterConfigVO == null) {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301051);
        }
        // 清空token
        CallCenterConfigEntity configEntity = new CallCenterConfigEntity();
        BeanUtils.copyProperties(callCenterConfigVO, configEntity);
        configEntity.setBatchCall(callSwitchBatchCallDTO.getBatchCall());
        Integer switchBatchCall = callCenterConfigModel.update(configEntity);
        if (switchBatchCall > 0) {
            callSwitchBatchCallVO.setBatchCall(configEntity.getBatchCall());
        } else {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301074);
        }
        return new XbbResponse<>(callSwitchBatchCallVO);
    }

    /**
     * 开启防骚扰策略（主要是销帮帮呼叫中心）
     *
     * @param callSwitchAutoOpenDisturbDTO 开启防骚扰策略（主要是销帮帮呼叫中心）入参
     * @return CallSwitchAutoOpenDisturbVO 开启防骚扰策略（主要是销帮帮呼叫中心）回参
     * @throws XbbException 销帮帮设定的异常
     * @author youli.chen
     * @version v1.0
     * @since v1.0
     */
    @Override
    public XbbResponse<CallSwitchAutoOpenDisturbVO> switchAutoOpenDisturb(CallSwitchAutoOpenDisturbDTO callSwitchAutoOpenDisturbDTO) throws XbbException {
        CallSwitchAutoOpenDisturbVO openDisturbVO = new CallSwitchAutoOpenDisturbVO();
        // 第一步查询公司开启的话务中心
        XbbResponse<CallCenterConfigVO> configResponse = getByCorpId(callSwitchAutoOpenDisturbDTO.getCorpid(), null);
        CallCenterConfigVO callCenterConfigVO = configResponse.getResult();
        if (callCenterConfigVO == null) {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301051);
        }
        CallCenterConfigEntity configEntity = new CallCenterConfigEntity();
        BeanUtils.copyProperties(callCenterConfigVO, configEntity);
        configEntity.setIsAntiDisturb(callSwitchAutoOpenDisturbDTO.getIsAntiDisturb());
        configEntity.setCallNumPerDay(callSwitchAutoOpenDisturbDTO.getCallNumPerDay());
        configEntity.setCallNumPerWeek(callSwitchAutoOpenDisturbDTO.getCallNumPerWeek());
        configEntity.setCallNumPerMonth(callSwitchAutoOpenDisturbDTO.getCallNumPerMonth());
        Integer switchAutoOpenDisturb = callCenterConfigModel.update(configEntity);
        if (switchAutoOpenDisturb > 0) {
            openDisturbVO.setIsAntiDisturb(configEntity.getIsAntiDisturb());
            openDisturbVO.setCallNumPerDay(configEntity.getCallNumPerDay());
            openDisturbVO.setCallNumPerWeek(configEntity.getCallNumPerWeek());
            openDisturbVO.setCallNumPerMonth(configEntity.getCallNumPerMonth());
        } else {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301075);
        }
        return new XbbResponse<>(openDisturbVO);
    }

    /**
     * 开启防封号规则（主要是销帮帮呼叫中心）
     *
     * @param callBlockRuleDTO 开启防封号规则（主要是销帮帮呼叫中心）入参
     * @return CallBlockRuleVO 开启防封号规则（主要是销帮帮呼叫中心）回参
     * @throws XbbException 销帮帮设定的异常
     * @author youli.chen
     * @version v1.0
     * @since v1.0
     */
    @Override
    public XbbResponse<CallBlockRuleVO> switchBlockRule(CallBlockRuleDTO callBlockRuleDTO) throws XbbException {
        CallBlockRuleVO callBlockRuleVO = new CallBlockRuleVO();
        // 第一步查询公司开启的话务中心
        XbbResponse<CallCenterConfigVO> configResponse = getByCorpId(callBlockRuleDTO.getCorpid(), null);
        CallCenterConfigVO callCenterConfigVO = configResponse.getResult();
        if (callCenterConfigVO == null) {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301051);
        }
        CallCenterConfigEntity configEntity = new CallCenterConfigEntity();
        BeanUtils.copyProperties(callCenterConfigVO, configEntity);
        configEntity.setCallBlockRule(callBlockRuleDTO.getCallBlockRule());
        configEntity.setCallBlockInterval(callBlockRuleDTO.getCallBlockInterval());
        configEntity.setCallBlockThirtyNum(callBlockRuleDTO.getCallBlockThirtyNum());
        configEntity.setCallBlockThirtySwitch(callBlockRuleDTO.getCallBlockThirtySwitch());
        configEntity.setCallBlockDayNum(callBlockRuleDTO.getCallBlockDayNum());
        configEntity.setCallBlockDaySwitch(callBlockRuleDTO.getCallBlockDaySwitch());
        configEntity.setCallBlockTriggerWay(callBlockRuleDTO.getCallBlockTriggerWay());
        Integer switchBlockRule = callCenterConfigModel.update(configEntity);
        if (switchBlockRule > 0) {
            callBlockRuleVO.setCallBlockRule(configEntity.getCallBlockRule());
            callBlockRuleVO.setCallBlockInterval(configEntity.getCallBlockInterval());
            callBlockRuleVO.setCallBlockThirtyNum(configEntity.getCallBlockThirtyNum());
            callBlockRuleVO.setCallBlockThirtySwitch(configEntity.getCallBlockThirtySwitch());
            callBlockRuleVO.setCallBlockDayNum(configEntity.getCallBlockDayNum());
            callBlockRuleVO.setCallBlockDaySwitch(configEntity.getCallBlockDaySwitch());
            callBlockRuleVO.setCallBlockTriggerWay(configEntity.getCallBlockTriggerWay());
        } else {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301075);
        }
        return new XbbResponse<>(callBlockRuleVO);
    }

    /**
     * 自定义设置有效通话时长（主要是销帮帮呼叫中心）
     *
     * @param callSetEffectiveTimeDTO 自定义设置有效通话时长（主要是销帮帮呼叫中心）入参
     * @return CallSetEffectiveTimeVO 自定义设置有效通话时长（主要是销帮帮呼叫中心）回参
     * @throws XbbException 销帮帮设定的异常
     * @author youli.chen
     * @version v1.0
     * @since v1.0
     */
    @Override
    public XbbResponse<CallSetEffectiveTimeVO> setEffectiveTime(CallSetEffectiveTimeDTO callSetEffectiveTimeDTO) throws XbbException {
        CallSetEffectiveTimeVO callSetEffectiveTimeVO = new CallSetEffectiveTimeVO();
        // 第一步查询公司开启的话务中心
        XbbResponse<CallCenterConfigVO> configResponse = getByCorpId(callSetEffectiveTimeDTO.getCorpid(), null);
        CallCenterConfigVO callCenterConfigVO = configResponse.getResult();
        if (callCenterConfigVO == null) {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301051);
        }
        CallCenterConfigEntity configEntity = new CallCenterConfigEntity();
        BeanUtils.copyProperties(callCenterConfigVO, configEntity);
        configEntity.setEffectiveTime(callSetEffectiveTimeDTO.getEffectiveTime());
        Integer setEffectiveTime = callCenterConfigModel.update(configEntity);
        if (setEffectiveTime > 0) {
            callSetEffectiveTimeVO.setEffectiveTime(configEntity.getEffectiveTime());
        } else {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301075);
        }
        return new XbbResponse<>(callSetEffectiveTimeVO);
    }
}
